<template>
  <div class="app-container" v-loading="pageLoading">
    <el-button type="primary" class="filter-item fr m" @click="createItem" v-permission="'sopItem.add'">创建
    </el-button>

    <div class="filter-container">
      <el-select class="filter-item" style="width: 200px;" @change="research" v-model="query.listType" placeholder="请选择"
        filterable clearable>
        <el-option :value="1" label="待我审批的"></el-option>
        <el-option :value="2" label="我创建的"></el-option>
      </el-select>
      <el-select class="filter-item" style="width: 200px;" @change="research" v-model="query.type" placeholder="请选择工艺类型"
        filterable clearable>
        <el-option v-for="(i,t) in typeOption" :key='t' :value="i.value" :label="i.label"></el-option>
      </el-select>
      <el-select class="filter-item" style="width: 200px;" @change="research" v-model="query.status" placeholder="请选择状态"
        filterable clearable>
        <el-option v-for="(val, key) in statusConfig" :key='key' :value="key" :label="val.name"></el-option>
      </el-select>
      <el-input style="width: 200px;" placeholder="输入工艺项按回车" clearable prefix-icon="el-icon-search" class="filter-item"
        @keyup.enter.native="research" @clear="research" v-model="query.query"></el-input>
      <!-- <el-date-picker @change="research" class="filter-item" style="width: 230px;" v-model="query.daterange"
        type="daterange" value-format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期"
        :picker-options="datePickerOption">
      </el-date-picker> -->
      <el-button class="filter-item" type="success" plain @click="research">查询</el-button>
      <el-button class="filter-item" type="info" plain @click="exportData" :loading="exportLoading">导出</el-button>
      <el-button type="warning" class="filter-item  ml-5" v-if="multiApproveArray.length>0" @click="openMultiModal"
        :loading="multiLoading" v-permission="'sopItem.edit'" plain>批量审核
      </el-button>
    </div>
    <div style="margin-bottom: 5px">

    </div>
    <z-table :list="list" @selectable="selectable" :tableProps="tableProps" :columns="columns"
      @selection-change='selectionChange'>
      <template v-slot:content="v">
        <div v-if="v.key == 'status'">
          <span class="text-label" :class="statusConfig[v.row[v.key]].style">
            {{statusConfig[v.row[v.key]].name}}
          </span>
        </div>
        <div v-else-if="v.key=='file_list'" style="text-align:center">
          <!-- <div v-if="v.row[v.key]">
            <div v-for="val in v.row[v.key]" :key="val.id">
              <a href="javascript:void" style="text-decoration:underline" class="text-blue"
                @click="download(val)">{{val.name}}</a>
            </div>
          </div> -->
          <swiper @imgClick='swiperClick' :nodialogShow='true' :slidesPerView='3' :spaceBetween="8" :videoPreview='true'
            :showData='v.row[v.key]' @videoClick='swiperClick'></swiper>
        </div>
        <span v-else>{{ v.row[v.key] }}</span>
      </template>
      <template v-slot:operation="v">
        <a href="#" class="text-blue" @click.prevent="editItem(v.row)" v-permission="'sopItem.edit'">查看</a>
        <a href="#" class="text-red" v-restrict='v.row.status==0' @click.prevent="deleteItem(v.row)"
          v-permission="'sopItem.delete'">删除</a>
        <a href="#" class="text-gray ml-5" @click.prevent="openLog(v.row)" v-permission="'sopItem.edit'">查看日志</a>
      </template>
    </z-table>
    <z-form-dialog :name="name" :data="data" :formProps="formProps" :fields="fields" :submitLoading="submitLoading"
      :visible.sync="editFormVisible">
      <template v-slot:footer>
        <launch :draftApi="api+'saveDraft'" v-if="isLaunch" :launchApi="api+'launch'" :callback="workflowFormatData"
          @workflowUpdateEmit="workflowUpdateEmit"></launch>
        <approve :modle="workFlow" v-if="isApprove" :approveApi="$api.workflow+'approveforms'"
          :backApi="$api.workflow+'back'" :reSubmitApi="api+'launch'" :revokeApi="$api.workflow+'revoke'"
          :callback="workflowFormatData" @workflowUpdateEmit="workflowUpdateEmit" :rejectApi="$api.workflow+'reject'"
          :form="data">
        </approve>
      </template>
    </z-form-dialog>
    <z-pagination :pagination="pagination" :total="total" :page.sync="query.page" :limit.sync="query.size"
      @change="getList"></z-pagination>
    <el-dialog title="日志记录" v-move :close-on-click-modal="true" :visible.sync="logShow" width="60%">
      <div>
        <approve-log :api="api+'getloglist'" v-if="logShow" :form="data"></approve-log>
      </div>
    </el-dialog>
    <el-dialog title="批量审批" v-move :close-on-click-modal="true" :visible.sync="multiVisible" width="50%">
      <z-form :formProps="{labelWidth:'100px'}" :fields="multiFields" :data="multiData"></z-form>
      <div class="text-right">
        <el-button @click="multiVisible = false">取消</el-button>
        <el-button v-if="!formProps.disabled" type="primary" @click.native="multiApprove" :loading="multiLoading">确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="true" class="swiper" :visible.sync="swiperShow" :show-close='false' width="70%"
      fullscreen>
      <div style="width:50px;height:50px;position:fixed;top:20px;right:20px;z-index:999"
        @click.stop="swiperShow = !swiperShow">
        <i class="el-icon-error t-46 text-white"></i>
      </div>
      <swiper v-if="swiperShow" :showData='swiperShowData' :initialSlide='initialSlide'></swiper>
    </el-dialog>
  </div>
</template>

<script>
import commonMixin from '@/views/_common/mixin'
import launch from '@/views/components/scWorkflow/launch'
import approve from '@/views/components/scWorkflow/approve'
import approveLog from '@/views/components/scWorkflow/approveLog'
import swiper from '@/views/components/swiper'
import dayjs from 'dayjs'
import { download } from '@/utils/index.js'

export default {
  mixins: [commonMixin],
  components: { launch, approve, approveLog, swiper },
  name: 'sopItem',
  data: function () {
    return {
      swiperShow: false,
      postForList: true,
      data: {},
      name: '工艺库管理',
      user: this.$store.state.user.user,
      multiApproveArray: [],
      dataDetail: {},
      statusConfig: {
        0: { style: 'bg-yellow', name: '草稿' },
        1: { style: 'bg-green', name: '审批中' },
        2: { style: 'bg-red', name: '已退回' },
        3: { style: 'bg-gray', name: '已撤销' },
        4: { style: 'bg-gray', name: '已拒绝' },
        5: { style: 'bg-blue', name: '已完成' },
      },
      statusOption: [{ value: 0, label: '' }],
      deleteArray: [],
      localFileArray: [],
      api: this.$api.sopItem,
      multipleSelection: [],
      multiLoading: false,
      multiFields: [{ title: '审批意见', key: 'comments', span: 24, name: 'textarea' }],
      multiData: {},
      multiVisible: false,
      logShow: false,
      logList: [],
      initData: {
        file: [],
      },
      workFlow: {}, // 流程id获取
      logData: {}, // 日志
      typeOption: [],
      tableLogLoading: false,
      columns: [
        { title: '工艺类型', key: 'typeName', width: 120 },
        { title: '工艺项名', key: 'name', width: 140 },
        { title: '工艺项描述', key: 'description', width: 140 },
        { title: '工艺项要求', key: 'requirement', width: 140 },
        { title: '操作图示', key: 'file_list', width: 260, resizable: false },
        { title: '当前关卡', key: 'workflow_item_name', width: 130 },
        { title: '当前审批人', key: 'current_approver', width: 140 },
        { title: '状态', key: 'status', width: 110 },
        { title: '创建人', key: 'create_user', width: 120 },
        { title: '创建时间', key: 'create_time', width: 150 },
        { title: '修改人', key: 'modify_user', width: 150 },
        { title: '修改时间', key: 'modify_time', width: 150 },
      ],
      logContent: '',
      fields: [
        {
          title: '工艺类型',
          key: 'type',
          span: 12,
          name: 'select',
          required: true,
          options: [],
          props: {
            filterable: true,
          },
        },
        { title: '工艺项名', key: 'name', span: 12, required: true },
        { title: '描述', key: 'description', span: 24, name: 'textarea' },
        { title: '技术要求', key: 'requirement', span: 24, name: 'textarea' },
        {
          title: '文件',
          key: 'file_list',
          name: 'fileUploader',
          props: {
            id: 'sopUpload',
            accept: '.jpg,.mp4,.png',
            limit: 5,
            multiple: true,
            'on-change': this.uploadOnchange,
            'before-remove': this.beforeRemove,
            'on-preview': this.onPreview,
            autoUpload: false,
            action: '',
          },
          span: 12,
        },
      ],
      swiperShowData: [],
      initialSlide: 0, // 展示
      tableProps: {
        border: true,
        opsColWith: 140, //不定义默认80
        hideOperations: false,
        selection: {
          showSelection: true,
          props: { selectable: this.selectable },
        }, // 是否开启复选
        showIndexCol: true,
      },
      query: {
        page: 1,
        size: 10,
        queryString: null,
        type: null,
        listType: 1,
        form_name: this.$options.name,
      },
    }
  },
  computed: {
    isApprove() {
      return this.data.status == 5 || this.data.status == 1 || this.data.status == 2
    },
    isLaunch() {
      return this.data.status == 0 || !this.data.status
    },
  },
  methods: {
    // 多选操作
    selectable(row) {
      if (row.current_approver) {
        let approverArray = row.current_approver.split(',')
        return row.status == 1 && approverArray.indexOf(this.user.userID) > -1
      }
      return false
    },
    selectionChange(val) {
      this.multiApproveArray = []
      val.forEach((v) => {
        this.multiApproveArray.push({ id: v.id, form_name: v.form_name, comments: '' })
      })
    },
    openMultiModal() {
      this.multiData = {}
      if (this.multiApproveArray.length <= 0) {
        this.$message.error('请先勾选要审批的记录')
        return false
      }
      this.multiVisible = true
    },
    multiApprove() {
      if (this.multiApproveArray.length <= 0) {
        this.$message.error('请先勾选要审批的记录')
        return false
      }
      this.multiApproveArray.forEach((v) => {
        v.comments = this.multiData.comments
      })
      this.multiData.comments
      this.multiLoading = true
      this.$request(this.$api.workflow + 'approveforms', this.multiApproveArray, 'post')
        .then((r) => {
          this.$message.success('批量审批成功')
          this.multiVisible = false
          this.getList()
        })
        .finally(() => {
          this.multiLoading = false
        })
    },
    workflowFormatData() {
      let tmp = ''
      //草稿或退回状态
      if (!this.data.status || this.data.status == 0 || this.data.status == 2) {
        let form = new FormData()
        let check = this.validataData(this.fields, this.data)
        if (!check) return false
        //处理log
        let content = this.logFormat()
        let data = {
          workflowData: this.workFlow,
          baseData: this.data,
          logData: { content: content ? content : '' },
          deleteArray: this.deleteArray,
        }
        form.append('model', JSON.stringify(data))
        this.localFileArray.forEach((v) => {
          form.append('files', v)
        })
        tmp = form
      } else {
        tmp = this.workFlow
      }

      return tmp
    },
    logFormat() {
      let o = this.dataDetail
      let v = this.data
      let logData = ''
      if (!v || !o || o.toString() == '{}' || v.status != 2 || v.id != o.id) return false
      if (o) {
        for (const key in v) {
          if (o[key] && v[key] !== o[key] && key != 'file_list') {
            let fieldObj = this.fields.find((v) => v.key == key)
            let fieldName = fieldObj ? fieldObj.title : key
            let value = ''
            if (key == 'type') {
              let typeObj = this.typeOption.find((v) => {
                return v.value == o[key]
              })
              value = typeObj.label
            }
            value = o[key]

            logData += fieldName + ':' + value + ';'
          }
        }
        if (this.deleteArray.length || this.localFileArray.length > 0) {
          let fileNameArray = []

          o.file_list.forEach((v) => {
            fileNameArray.push(v.name)
          })
          logData += '文件:' + fileNameArray.join(',')
        }
      }
      return logData
    },
    workflowUpdateEmit() {
      this.getList()
      this.editFormVisible = false
    },
    getFileType(url) {
      var spl = url.split('.')
      return spl[spl.length - 1]
    },
    formatList(data) {
      let tmp = _.cloneDeep(data)
      tmp.forEach((i) => {
        i.file_list.forEach((k) => {
          k.type = this.getFileType(k.url)
          k.url = this.$api.baseUrl.replace('api/', '') + k.url
        })
        this.typeOption.map((j) => {
          if (i.type == j.value) {
            i.typeName = j.label
          }
        })
      })
      return tmp
    },

    formatQuery(query) {
      let tmp = _.cloneDeep(query)
      if (tmp.daterange) {
        tmp.begintime = tmp.daterange[0]
        tmp.endtime = tmp.daterange[1]
        delete tmp.daterange
      }
      return tmp
    },
    exportData() {
      let url = this.apiList || this.api + 'getlist'
      let query = this.formatQuery(this.query)
      query.page = 1
      query.size = 99999
      this.exportLoading = true
      this.$request(url, query, this.postForList ? 'post' : 'get')
        .then((r) => {
          let exprotList = _.cloneDeep(r.list)

          exprotList.forEach((i) => {
            i.status = this.statusConfig[i.status].name
            this.typeOption.forEach((j) => {
              if (i.type == j.value) {
                i.typeName = j.label
              }
            })
            let tmpArray = []
            i.file_list.forEach((v) => {
              tmpArray.push(v.name)
            })
            i.file_list = tmpArray.join(';')
          })
          import('@/vendor/Export2Excel').then((excel) => {
            const filterVal = this.columns.map((item) => {
              return item.key
            })
            const tHeader = this.columns.map((item) => {
              return item.title || item.key
            })
            const data = exprotList.map((v) => filterVal.map((j) => v[j]))
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: this.name + '_' + dayjs().format('YYYYMMDD'),
            })
          })
        })
        .finally(() => {
          this.exportLoading = false
        })
    },
    // 打开日志
    openLog(row) {
      this.data = row
      this.logShow = true
    },
    onPreview(file) {
      if (file.url && (file.url.indexOf('http://') > -1 || file.url.indexOf('https://'))) this.download(file)
    },
    uploadOnchange(file, fileList) {
      let f = file.raw
      if (f.type == 'image/png' || f.type == 'image/jpeg' || f.type == 'image/jpg') {
        if (f.size < 10 * 1024 * 1024) {
          this.localFileArray.push(f)
        } else {
          this.$message.error('图片 大小限制10M')
          fileList.splice(fileList.indexOf(f), 1)
        }
      } else if (f.type == 'video/mp4') {
        if (f.size < 40 * 1024 * 1024) {
          this.localFileArray.push(f)
        } else {
          this.$message.error('视频 大小限制40M')
          fileList.splice(fileList.indexOf(f), 1)
        }
      }
    },
    beforeRemove(file) {
      if (file.id) {
        this.deleteArray.push(file.id)
        let fileArray = this.data.file_ids.split(',')
        let fileArrayTmp = fileArray.filter((v) => {
          return v != file.id
        })
        this.data.file_ids = fileArrayTmp.join(',')
      } else {
        this.localFileArray = this.localFileArray.filter((v) => {
          return v.uid != file.uid
        })
      }
    },
    createItem() {
      this.dataDetail = {}
      this.setFieldsDisable(false, ['type', 'name', 'description', 'requirement', 'file_list'])
      this.deleteArray = []
      this.localFileArray = []
      this.form = new FormData()
      this.data = _.cloneDeep(this.initData)
      this.editFormVisible = true
      this.$nextTick(() => {
        let idUp = document.getElementById('sopUpload')
        idUp.__vue__.clearFiles()
      })
    },
    // 编辑
    editItem(v) {
      this.dataDetail = _.cloneDeep(v)
      this.logData = {}
      this.pageLoading = true
      let url = this.api + 'getbyid'
      this.$request(url, {
        id: v.id,
        formName: 'sopItem',
      })
        .then((r) => {
          this.data = this.formatAfterGet(r)
          let booltmp =
            this.data.status == 0 ||
            !this.data.status ||
            (this.data.status == 2 && this.data.create_user == this.user.userID)
          this.setFieldsDisable(!booltmp, ['type', 'name', 'description', 'requirement', 'file_list'])
          this.editFormVisible = true
          this.deleteArray = []
          this.localFileArray = []
        })
        .finally(() => {
          this.pageLoading = false
        })
    },
    deleteItem(v) {
      if (v.status != 0) return
      this.$confirm('确定要删除这条记录？').then(() => {
        this.pageLoading = true
        let url = this.apiDelete || this.api + 'delete'
        this.$request(url + '/' + v.id + '/sopItem', {}, 'post')
          .then((r) => {
            this.$message.success('操作成功')
            this.getList()
          })
          .finally(() => {
            this.pageLoading = false
          })
      })
    },
    async arrToObj(arr) {
      let obj = {}
      arr.map((item) => {
        obj_obj[item.label] = item.value
      })
      return await obj
    },
    download(file) {
      download(this.$api.baseUrl, file)
    },
    // 预览点击
    swiperClick(data, t) {
      this.swiperShowData = data
      this.initialSlide = t
      this.swiperShow = true
    },
  },

  created: function () {
    this.$request(this.$api.dictionary + 'getdirectchildren', {
      parentType: 'process_type',
    }).then((r) => {
      this.getFieldConfig('type').options = r
      this.typeOption = r
      this.getList()
    })
    this.$request(this.$api.workflow + 'GetWorkFlowIdByPage?formName=' + this.$options.name).then((r) => {
      this.workFlow = {
        form_name: this.$options.name,
      }
    })
  },
  mounted() {
    this.$nextTick(() => {
      // this.$refs.table.doLayout()
    })
  },
}
</script>

<style scoped>
.swiper ::v-deep .el-dialog {
  background-color: rgba(0, 0, 0, 0);
  padding: 30px 100px 0;
  box-sizing: border-box;
  /* height: 100%; */
}
.swiper ::v-deep .el-dialog__header {
  padding: 0;
}
.swiper ::v-deep .el-dialog__body {
  padding: 0;
  background-color: rgba(0, 0, 0, 0.001);
}
</style>
